package top.wardyan.wtask.ctrl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hutool.core.collection.CollectionUtil;
import top.wardyan.base.common.util.DateUtil;
import top.wardyan.common.ctrl.BaseController;
import top.wardyan.wtask.model.YTDevreport;
import top.wardyan.wtask.service.IProcService;
import top.wardyan.wtask.service.IYTDevreportService;
import top.wardyan.wtask.tapd.util.TapdUtil;

@Path("/devreport")
public class ReportCtrl extends BaseController{
	
	@Inject IProcService procService;
	@Inject IYTDevreportService devreportService;

	private static final cn.hutool.log.Log log = cn.hutool.log.Log.get();
	
	public void index() {
		this.renderNull();
	}
	
	
	/**
	 * 填写新单据
	 */
	public void add() {
		Timestamp now = DateUtil.getCurrentTimestamp();
		Timestamp begin = TapdUtil.getWeekBeginTime(now);
		this.set("begintime", begin);
		this.set("endtime", TapdUtil.getWeekEndTime(now));
		this.set("xEmergencyDeadline", new Timestamp(begin.getTime() + 1000 * 60 * 60 * 24 * 5));
		this.renderTemplate("add.html");
	}
	
	/**
	 * 保存新单据
	 */
	public void save(Timestamp beginTime, Timestamp endTime, Float dayCnt, Float hour, Float cost, Timestamp deadline) {
		
		if(deadline == null) {
			deadline = endTime;
		}
		Integer id = procService.yp_getid("yt_devreport", "sID", 1);
		Record data = new Record();
		data.set("sID", id);
		data.set("xBeginTime", beginTime);
		data.set("xEndTime", endTime);
		data.set("xDayCnt", dayCnt);
		data.set("xHours", hour);
		data.set("xCost", cost);
		data.set("xDateTime", DateUtil.range(1))
		.set("xDataType", 1)
		.set("sStatus", 2)
		.set("sVerNo", 1)
		.set("sOwner", "Admin")
		.set("sCreateDate", DateUtil.getCurrentTimestamp())
		.set("sLastUpdate", DateUtil.getCurrentTimestamp())
		.set("xEmergencyDeadline", deadline)
		;
		
		Db.save("yt_devreport", "sID", data);
		this.show(id);
	}
	
	private List<Timestamp> getDateList(Timestamp begin, Timestamp end){
		List<Timestamp> rs = new ArrayList<>();
		if(begin == null) {
			begin = DateUtil.getCurrentTimestamp();
		}
		if(end == null) {
			end = DateUtil.getCurrentTimestamp();
		}
		Timestamp start = begin;
		//rs.add(DateUtil.range(start, 1));
		while(start.getTime() < end.getTime()){
			rs.add(DateUtil.range(start, 1));
			start = new Timestamp(start.getTime() + 1000 * 60 * 60 * 24);
		}
		return rs;
	}
	
	
	/** 显示单据 **/
	public void show(Integer id){
		Record main = Db.findById("yt_devreport", "sID", id);
		//var ts = procService.yp_devreport_team_view(id);
		List<Record> items = procService.yp_devreport_item_view(id);
		List<Record> dates = procService.yp_devreport_date_view(id);
		this.set("custhour1", procService.yp_devreport_custhour_view(id, 1));
		this.set("custhour2", procService.yp_devreport_custhour_view(id, 2));
		this.set("custhour3", procService.yp_devreport_custhour_view(id, 3));
		this.set("custhour4", procService.yp_devreport_custhour_view(id, 4));
		this.set("dates", dates);
		this.set("hours", procService.yp_devreport_hour_view(id));
		this.set("teams", procService.yp_devreport_team_view(id));
		this.set("tasks", procService.yp_devreport_task_view(id));
		this.set("emergencys", procService.yp_devreport_emergency_view(id));
		this.set("items", items);
		this.set("feishus", procService.yp_devreport_feishu_view(id));
		this.set("mans", procService.yp_listempls(true));
		
//		List<Record> groups = procService.yp_listgroups();
//		this.set("groups", groups);
		
		List<Timestamp> ds = dates.stream().map(new Function<Record,Timestamp>(){
			@Override
			public Timestamp apply(Record t) {
				return t.getTimestamp("xDate");
			}
		}).distinct().sorted(new Comparator<Timestamp>() {

			@Override
			public int compare(Timestamp a, Timestamp b) {
				return Long.compare(a.getTime(), b.getTime());
			}
			
		}).collect(Collectors.toList());
		
		this.set("ds", getDateList(main.getTimestamp("xBeginTime"), main.getTimestamp("xEndTime")));
		
		
		List<String> dids =
				items.stream().map(new Function<Record, String>(){

			@Override
			public String apply(Record t) {
				return t.getStr("dID");
			}
			
		}).distinct().collect(Collectors.toList());
		
		main.put("dids", CollectionUtil.join(dids, ","));
		this.set("main", main);
		this.renderTemplate("show.html");
	}
	
	public void build(Integer sID) {
		procService.yp_devreport_build(sID);
		this.show(sID);
	}
	
	public void delete(Integer id) {
		Db.update("update yt_devreport set sStatus = 1 where sID = ?", id);
		this.list(null, null, 1, 20);
	}
	
	public void list(Timestamp begin, Timestamp end, Integer pageNo, Integer pageSize) {
		if(begin == null) {
			begin = DateUtil.range(11);
		}
		if(end == null) {
			end = DateUtil.range(2);
		}
		if(pageNo == null) {
			pageNo = 1;
		}
		if(pageSize == null) {
			pageSize = 20;
		}
		end = DateUtil.range(end, 2);
		List<Record> datas = procService.yp_devreport_view(begin, end, 0, pageNo, pageSize);
		this.set("datas", datas);
		this.set("begin", begin);
		this.set("end", end);
		this.set("pageNo", pageNo);
		this.set("pageSize", pageSize);
		this.renderTemplate("list.html");
	}
	
	public void update() {
		// Integer id = this.getInt("sID");
		YTDevreport main = this.getModel(YTDevreport.class, "");
		devreportService.update(main);
		this.show(main.getSID());
		
	}
	
	public void audit(Integer sID) {

		Db.update("update yt_devreport set sStatus = 5 where sID = ?", sID);
		this.list(null, null, 1, 20);
	}
	
	
	public void saveedit() {
		Integer mID = this.getParaToInt("mID");
		String m = String.valueOf(mID);;
		String _dids = this.getPara("dids");
		if(_dids == null) {
			_dids = "";
		}
		Map<String, String[]> _datas = this.getParaMap();
		Map<String, String> datas = new HashMap<>() {{
			Set<String> keys = _datas.keySet();
			for(String key : keys) {
				String value = _datas.get(key) != null && _datas.get(key).length > 0 ? _datas.get(key)[0]: "";
				this.put(key, value);
			}
		}};
		
		String[] dids = _dids.split(",");
		
		Set<String> datakeys = datas.keySet();
		
		for(String did : dids) {
			Record detail = new Record();
			
			detail.set("mID", mID);
			detail.set("dID", Integer.valueOf(did));
			
			
			for(String dk : datakeys) {
				String prefix = m + "_" + did + "_";
				if(dk.startsWith(prefix)) {
					String field = dk.substring(prefix.length());
					String value = datas.get(dk);
					detail.set(field, value);
				}
			}
			
			try {
				Db.update("yt_devreport_item", "mID,dID", detail);
			}catch(Exception e) {
				log.error(e);
			}
		}

		procService.yp_devreport_build_mark(mID);
		this.show(mID);
	}

}
